import { getMyMenuHandle, getMyMenus } from '@/api/user'
import {
  authMenu,
  formatRoutes,
  saveMenuHandleIds,
  saveMenuHandleMap,
  saveMenuMap
} from '@/util/menu'
import { getJwt, getUseRoleId, setUserMenus } from '@/util/token'
import { ElMessage } from 'element-plus'
import { createRouter, createWebHistory } from 'vue-router'
import { Progress } from '@/util/progress'

let progress = new Progress()
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/home' },
    {
      path: '/sign',
      component: () => import('@/views/sign/Index.vue'),
      children: [
        { path: 'login', name: 'login', component: () => import('@/views/sign/in/Index.vue') },
        {
          path: 'register',
          name: 'register',
          component: () => import('@/views/sign/up/Index.vue')
        }
      ]
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/home/Home.vue'),
      children: [
        {
          name: 'user_index',
          path: 'user_index',
          meta: {
            name: '个人中心'
          },
          component: () => import('@/views/user/Index.vue')
        }
      ]
    },
    { path: '/:pathMatch(.*)*', component: () => import('@/views/error/404.vue') }
  ]
})

let isFrist = true
router.beforeEach((to, from, next) => {
  // 判断路由是否为首次加载
  progress.start()
  if (isFrist) {
    if (to.name == 'login' || to.name == 'register') {
      next()
      return
    }
    if (getJwt()) {
      let rid = getUseRoleId()
      if (rid !== null) {
        getMyMenus().then((menus) => {
          const routesData = formatRoutes(menus.data)
          // 保存菜单原始数据
          setUserMenus(menus.data)
          saveMenuMap(menus.data)
          routesData.forEach((r) => {
            router.addRoute('home', r)
          })
          console.log('roter-loaded')
          if (authMenu(to.path)) {
            next(to.path)
          } else {
            next(from.path)
          }
        })
        // 获取 用户菜单按钮 并保存
        getMyMenuHandle(rid).then((d) => {
          saveMenuHandleMap(d.data.smh)
          saveMenuHandleIds(d.data.tags)
        })
      } else {
        if (from.name !== 'home') {
          next({ name: 'home' })
        }
      }
    } else {
      ElMessage.warning('请登录过后再操作')
      next({
        name: 'login'
      })
    }
    isFrist = false
  } else {
    if (authMenu(to.path)) {
      next()
    }
  }
})

let loadingRemove = true
router.afterEach(() => {
  if (loadingRemove) {
    document.getElementById('loding-box')?.remove()
    loadingRemove = false
  }
  progress.end()
})
export default router
